package com.molyfun.parents.activity.setting;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.Window;
import android.widget.Toast;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.fragment.dialog.CommonChooseDialogFragment;
import com.molyfun.parents.rest.bean.CheckVersionResponse;
import com.molyfun.parents.service.DownloadApkService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UpdateActivity extends BaseActivity {

    private static final String FLAG_SHOW_TOAST = "show_toast";

    private boolean mShowToast = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        mShowToast = getIntent().getBooleanExtra(FLAG_SHOW_TOAST, true);
        checkVersion();
    }

    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUESTCODE_1 = 1057;
    private String apkDownloadUrl;

    public static final void startActivity(Context context){
        Intent intent = new Intent();
        intent.setClass(context, UpdateActivity.class);
        context.startActivity(intent);
    }

    public static final void startActivity(Context context, boolean toast){
        Intent intent = new Intent();
        intent.setClass(context, UpdateActivity.class);
        intent.putExtra(FLAG_SHOW_TOAST, toast);
        context.startActivity(intent);
    }

    /**
     * 启动下载apkService
     */
    private void downLoadApk() {
        if (Build.VERSION.SDK_INT >= 23) {
            if(getPackageManager().checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_PERMISSION_REQUESTCODE_1);
                return;
            }
        }
        Intent intent = new Intent(this, DownloadApkService.class);
        intent.putExtra("apk_url",apkDownloadUrl);
        startService(intent);
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case WRITE_EXTERNAL_STORAGE_PERMISSION_REQUESTCODE_1:
                if (grantResults[0] == 0){
                    downLoadApk();
                }else {
                    finish();
                }
                break;
        }
    }

    private void checkVersion(){
        showProgressDialog();
        Call<CheckVersionResponse> call = MFPApplication.getInstance().getRestClient().checkVersion(MFPApplication.sVersionName);
        call.enqueue(new Callback<CheckVersionResponse>() {
            @Override
            public void onResponse(Call<CheckVersionResponse> call, Response<CheckVersionResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (!"0".equals(response.body().getData().getState())) {
                            apkDownloadUrl = response.body().getData().getVersionurl();

                            new CommonChooseDialogFragment.CommonChooseDialogBuilder(response.body().getData().getContent())
                                    .setCommonChooseDialogClickListener(new CommonChooseDialogFragment.CommonChooseDialogClickListener() {
                                        @Override
                                        public void onConfirm() {
                                            downLoadApk();
                                        }

                                        @Override
                                        public void onCancel() {
                                            finish();
                                        }
                                    })
                                    .build(getSupportFragmentManager().beginTransaction());

                            return;
                        } else {
                            if(mShowToast){
                                toast("已经是最新版本", Toast.LENGTH_SHORT);
                            }
                            finish();
                        }
                    }else{
                        finish();
                    }
                }else{
                    finish();
                }
            }

            @Override
            public void onFailure(Call<CheckVersionResponse> call, Throwable t) {
                dismissProgressDialog();
                finish();
            }
        });
    }


}
